#include "DBFile.h"

DBFile::DBFile(){}

DBFile::~DBFile(){
	delete genericDBFile ;
};

int DBFile :: Create (char *f_path, fType f_type, void *startup){
	if (f_type == heap){
	    genericDBFile = new HeapDBFile;
		genericDBFile->Create(f_path, f_type, NULL);
	}

	else if (f_type == sorted){
		genericDBFile = new SortedDBFile;
		genericDBFile -> Create(f_path, f_type, startup);
    }

	else return 0;

	return 1;
}

int DBFile :: Open (char *fpath){
	char metadataPath[250], type;

	sprintf (metadataPath, "%s.header", fpath);
	FILE *metadata = fopen (metadataPath, "r");

	if(metadata != NULL){
        fread (&type, 1, 1, metadata);

        if (type == 'h'){
            genericDBFile = new HeapDBFile;

            if (genericDBFile->Open(fpath)){
                fclose(metadata);
                return 1;
            }
        }

        else if (type == 's'){
              fclose(metadata);
              genericDBFile = new SortedDBFile;
              return genericDBFile->Open(fpath);
        }
    }

    else
        cout << endl << "Could not open metadata file! " << metadataPath << endl;

    return 0;
}

int DBFile :: Close (){
	return genericDBFile->Close();
}

void DBFile :: Load (Schema &myschema, char *loadpath){
	genericDBFile->Load (myschema, loadpath);
}

void DBFile :: MoveFirst (){
	genericDBFile->MoveFirst();
}

void DBFile :: Add (Record &addme){
	genericDBFile->Add(addme);
}

int DBFile :: GetNext (Record &fetchme){
	return genericDBFile->GetNext(fetchme);
}

int DBFile :: GetNext (Record &fetchme, CNF &cnf, Record &literal){
	return genericDBFile->GetNext(fetchme, cnf, literal);
}


